package main

import (
	"fmt"
	"net/http"
)

// Start 启动服务
func Start() {
	log.Info("start...")
	// listen and serve
	GraceRun(fmt.Sprintf(":%d", httpPort), &HookHandler{})
}

type HookHandler struct {
}

func (handler *HookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	cmd := fmt.Sprintf("%s/%s", appPath, scriptFileName)
	err := SendTask(cmd)
	if err != nil {
		renderErr(w, err)
		return
	}
	fmt.Fprintf(w, "success")
}

func renderErr(w http.ResponseWriter, err error) {
	log.Error(err)
	switch err {
	case ErrTimeout:
		fmt.Fprintf(w, "%d - %s", http.StatusOK, err.Error())
	default:
		fmt.Fprintf(w, "%d - %s", http.StatusBadRequest, err.Error())
	}
}
